package com.luoxiang.socialandroid.fragment;

import static android.content.Context.LOCATION_SERVICE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.lib_common.common.Constants;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.DetailsActivity;
import com.luoxiang.socialandroid.activity.GetimageActivity;
import com.luoxiang.socialandroid.activity.TestActivity;
import com.luoxiang.socialandroid.adapter.TcRecyAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.BeforeCallBean;
import com.luoxiang.socialandroid.bean.GetMessageBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.OurinfoBean;
import com.luoxiang.socialandroid.bean.THost;
import com.luoxiang.socialandroid.bean.Typehost2Bean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.base.CallParam;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class TongchengFragment extends LazyLoadFragment {
    private RecyclerView rc_tc;
    private String token;
    private TcRecyAdapter adapter;
    private String mUserid;
    private int page = 1;//是我们的页数
    private List<THost> list;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private SmartRefreshLayout smartRefreshLayout;
    private StringBuilder stringBuilder;
    private TextView tvNOquanxian;
    private Boolean isLoad = false;

    @Override
    protected int setContentView() {
        return R.layout.fragment_tongcheng;
    }

    @Override
    protected void initView() {
        mUserid = MmkvUtil.INSTANCE.decodeString(ACCID);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        rc_tc = findViewById(R.id.rc_tongcheng);
        tvNOquanxian = findViewById(R.id.tvNOquanxian);
        smartRefreshLayout = findViewById(R.id.smartRefresh);
    }

    @Override
    protected void lazyLoad() {
        initScreenRecorderBuild();
        list = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rc_tc.setLayoutManager(linearLayoutManager);
        adapter = new TcRecyAdapter();
        rc_tc.setAdapter(adapter);
        getDysetting();
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoad = false;
                page++;
                getDysetting();
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isLoad = false;
                page = 1;
                getDysetting();
            }
        });
        tvNOquanxian.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                initScreenRecorderBuild();
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getRequest();

    }

    public void getDysetting() {
        if (isLoad) return;
        isLoad = true;
        String token = MmkvUtil.INSTANCE.decodeString(Constants.MmkvConst.TOKEN);
        if (stringBuilder != null) {
            if (judgeContainsStr(stringBuilder.toString())) {
                getTypeHosts(token, EXTRA, 4, "", page, "10");
                return;
            }
            getTypeHosts(token, EXTRA, 4, stringBuilder.toString(), page, "10");
        } else {
            getTypeHosts(token, EXTRA, 4, "", page, "10");
        }
    }

    public boolean judgeContainsStr(String str) {
        String regex = ".*[a-zA-Z]+.*";
        Matcher m = Pattern.compile(regex).matcher(str);
        return m.matches();
    }

    private void initScreenRecorderBuild() {
        RxPermissions rxPermissions = new RxPermissions(getActivity());
        rxPermissions.request(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION

        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    getlocation();
                    tvNOquanxian.setVisibility(View.GONE);
                } else {
                    tvNOquanxian.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void getlocation() {
        LocationManager locationManager = (LocationManager) requireActivity().getSystemService(LOCATION_SERVICE);
        //设置每一秒获取一次location信息
        if (ActivityCompat.checkSelfPermission(requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(requireActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

        }
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,      //GPS定位提供者
                1000,       //更新数据时间为1秒
                1,      //位置间隔为1米
                //位置监听器
                new LocationListener() {  //GPS定位信息发生改变时触发，用于更新位置信息

                    @Override
                    public void onLocationChanged(Location location) {
                        //GPS信息发生改变时，更新位置
                        //这里有回调就说明定位成功了

                        locationUpdates(location);
                    }

                    @Override
                    //位置状态发生改变时触发
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    @Override
                    //定位提供者启动时触发
                    public void onProviderEnabled(String provider) {
                        getDysetting();
                    }

                    @Override
                    //定位提供者关闭时触发
                    public void onProviderDisabled(String provider) {
                    }
                });
        //从GPS获取最新的定位信息
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        locationUpdates(location);    //将最新的定位信息传递给创建的locationUpdates()方法中

    }

    public void locationUpdates(Location location) {  //获取指定的查询信息
        //如果location不为空时
        if (location != null) {
            stringBuilder = new StringBuilder();        //使用StringBuilder保存数据
            //获取经度、纬度、等属性值
            stringBuilder.append(location.getLongitude() + ",");
            stringBuilder.append(location.getLatitude());
//            stringBuilder.append("\n精确度：");
//            stringBuilder.append(location.getAccuracy());
//            stringBuilder.append("\n高度：");
//            stringBuilder.append(location.getAltitude());
//            stringBuilder.append("\n方向：");
//            stringBuilder.append(location.getBearing());
//            stringBuilder.append("\n速度：");
//            stringBuilder.append(location.getSpeed());
//            stringBuilder.append("\n时间：");
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH mm ss");    //设置日期时间格式
//            stringBuilder.append(dateFormat.format(new Date(location.getTime())));
            com.luoxiang.socialandroid.utils.LogUtils.i("locationssss", stringBuilder.toString());
            getDysetting();
        } else {
            //否则输出空信息
            com.luoxiang.socialandroid.utils.LogUtils.i("locationssss", "没有获取到GPS信息");
        }
    }

    private void getTypeHosts(String token, String extra, int i, String locationstr, int page, String limit) {
        NetUtils2.getInstance().getApiService().getTypeHosts(token, extra, "4", locationstr, page, limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStrtongcheng", decryptStr);
                            Gson gson = new Gson();
                            Typehost2Bean bean = gson.fromJson(decryptStr, Typehost2Bean.class);
                            if (list != null) {
                                if (page == 1) {
                                    list.clear();
                                }
                            }


                            if (bean.getData() != null && bean.getData().getHosts() != null && bean.getData().getHosts().size() > 0) {
                                if (list != null) {
                                    list.addAll(bean.getData().getHosts());
                                }
                                adapter.setData(list);
                                adapter.notifyDataSetChanged();
                                adapter.setOnAddClickListenerDs(new TcRecyAdapter.OnAddClickListenerDs() {
                                    @Override
                                    public void onItemClicksDs(int position, int userid) {

                                        sayhello(token, EXTRA, userid);
                                        getDysetting();


                                    }
                                });
                                adapter.setOnAddClickListenerSx(new TcRecyAdapter.OnAddClickListenerSx() {
                                    @Override
                                    public void onItemClicksSx(int userid) {
                                        if (mUserid.equals(String.valueOf(userid))) {
                                            ToastUtils.showShort(R.string.mi_bunenghezijiliaotian);
                                        } else {
                                            XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(RouterConstant.CHAT_KRY, new UserInfo(userid + "", "aaa", "")).withContext(getActivity()).navigate();
                                        }
                                    }
                                });
                                adapter.setOnAddClickListenerShipin(new TcRecyAdapter.OnAddClickListenerShipin() {
                                    @Override
                                    public void onItemClicksShipin(int userid) {
                                        //跳转视频通话
                                        getimPre(EXTRA, userid + "", token);
                                    }
                                });
                            } else {
                                ToastUtils.showShort(R.string.mi_wugengduoshuju);
                            }

                            if (bean != null) {
                                if (bean.getData() != null) {
                                    if (bean.getData().getHosts() != null && bean.getData().getHosts().size() != 0) {

                                        adapter.setOnAddClickListener(new TcRecyAdapter.OnAddClickListener() {
                                            @Override
                                            public void onItemClicks(int userid) {
                                                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                                intent.putExtra("userid", userid);
                                                startActivity(intent);
                                            }
                                        });


                                    }
                                }
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                        LogUtils.i("error", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }
                });
    }

    private void getimPre(String extra, String toUserId, String token) {
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        OurinfoBean bean = gson.fromJson(decryptStr, OurinfoBean.class);
                        TestActivity.ourinfoBean = bean;
                        if (bean.getCode() == 0) {
                            //可以发起通话
                            int accId = MmkvUtil.INSTANCE.decodeInt(ACCID);
                            String id = UUID.randomUUID().toString().replace("-", "");
                            CallParam param = CallParam.createSingleCallParam(2, accId + "", toUserId + "", null, null, id);
                            CallKitUI.startSingleCall(getContext(), param);
                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }
                });

    }

    private void sayhello(String token, String extra, int userid) {
        NetUtils2.getInstance().getApiService().sayHello(token, extra, userid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStrdazhaohu", decryptStr);
                        Gson gson = new Gson();
                        GetMessageBean getMessageBean = gson.fromJson(decryptStr, GetMessageBean.class);
                        if (getMessageBean.getCode() == 0) {

                        } else {
                            ToastUtils.showShort(getMessageBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}